//
//  EJSLoginViewController.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2017/12/29.
//  Copyright © 2017年 lifayu. All rights reserved.
//

#import "EJSLoginViewController.h"
#import "EJSGetPhoneCodeRequest.h"
#import "EJSRegisteRequest.h"
#import "EJSRegisteProtocolViewController.h"
#import <UIView+BlocksKit.h>
#import "EJSInputValiCodeViewController.h"
#import "DJShowSelectTool.h"
#import "WXApiManager.h"
#import "EJSLoginRequest.h"
#import "EJSCountryListRequest.h"
#import "ZLProgressHUD.h"

@interface EJSLoginViewController ()<UITextFieldDelegate, WXAuthDelegate>
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UIButton *ensureButton;
@property (weak, nonatomic) IBOutlet UILabel *countryCodeLabel;
@property (copy, nonatomic) NSString *countryCode;

@property(strong,nonatomic)NSArray<EJSCountryModel*>*countryList;
@end

@implementation EJSLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self fetchCountryList];
    FlyWeakSelf
    [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        if(weakSelf.textField.text.length > 0 )
        {
            weakSelf.ensureButton.enabled = YES;
        }
        else
        {
            weakSelf.ensureButton.enabled = NO;
        }
    }];
   
}

-(void)fetchCountryList{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    FlyWeakSelf
    EJSCountryListRequest *req = [EJSCountryListRequest new];
    ZLProgressHUD *hud = [[ZLProgressHUD alloc] init];
    [hud show];
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [hud hide];
        weakSelf.countryList = response.data;
        [weakSelf configureCountryLabel:response.data[0]];
    } failHandler:^(BaseResponse *response) {
        [hud hide];
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     [self.navigationController setNavigationBarHidden:YES];
}

- (void)configOwnViews{
    UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [clearButton setImage:[UIImage imageNamed:@"eliminate"] forState:UIControlStateNormal];
    [clearButton addTarget:self action:@selector(clearTextField:) forControlEvents:UIControlEventTouchUpInside];
    [clearButton sizeToFit];
    self.textField.rightView = clearButton;
    self.textField.rightViewMode = UITextFieldViewModeAlways;
    [self.ensureButton setBackgroundImage:[UIImage fly_imageWithColor:UIColorFromRGB(0xD0D5D8)] forState:UIControlStateDisabled];
    [self.ensureButton setBackgroundImage:[UIImage fly_imageWithColor:AppMainColor] forState:UIControlStateNormal];
    self.countryCode = @"+34";

    [self.countryCodeLabel bk_whenTapped:^{
        [self.view endEditing:YES];
        [self changeCountryCode];
    }];
}

- (void)changeCountryCode{

    if (self.countryList.count == 0) {
        [self fetchCountryList];
        return;
    }
    NSMutableArray *newContryList = [NSMutableArray array];
    for (EJSCountryModel *model in self.countryList) {
        NSString *str = [NSString stringWithFormat:@"%@    %@",model.name,model.attribution];
        [newContryList addObject:str];
    }
    FlyWeakSelf
    [DJShowSelectTool showSelectWithArr:newContryList andDefaultStr:nil complete:^(NSString *selectedStr, NSInteger num) {
//        weakSelf.countryCode = weakSelf.countryList[num].attribution;
        [weakSelf configureCountryLabel:weakSelf.countryList[num]];
    }];
}

//- (void)setCountryCode:(NSString *)countryCode {
//    if(_countryCode != countryCode){
//        _countryCode = countryCode;
//        if(_countryCode){
//            [EJSUserModel saveCountryCode:_countryCode];
//            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@  ▼",_countryCode]];
//            [attr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:11] range:NSMakeRange(_countryCode.length, attr.length-_countryCode.length)];
//            [attr addAttribute:NSForegroundColorAttributeName value:AppMainColor range:NSMakeRange(_countryCode.length, attr.length-_countryCode.length)];
//            self.countryCodeLabel.attributedText = attr;
//        }
//    }
//}

-(void)configureCountryLabel:(EJSCountryModel*)model{
    self.countryCode = model.attribution;
    self.countryCodeLabel.text = model.name;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if(textField.text && textField.text.length > 0){
        self.ensureButton.enabled = YES;
    }else{
        self.ensureButton.enabled = NO;
    }
    return YES;
}

- (void)clearTextField:(UIButton *)sender {
    self.textField.text = nil;
    self.ensureButton.enabled = NO;
}

- (IBAction)backAction:(UIButton *)sender {
    [super leftBarButtonAction:nil];
}

- (IBAction)ensureAction:(UIButton *)sender {
    NSString *phone = self.textField.text;
    FlyWeakSelf
    EJSGetPhoneCodeRequest *req = [EJSGetPhoneCodeRequest new];
    req.phone = phone;
    req.countryCode = self.countryCode;
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        EJSInputValiCodeViewController *inputCodeVC = [[EJSInputValiCodeViewController alloc] initWithNibName:@"EJSInputValiCodeViewController" bundle:nil];
        inputCodeVC.phone = phone;
        [weakSelf presentViewController:inputCodeVC animated:NO completion:^{
            
        }];
        
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

- (IBAction)wechatLoginAction:(UIButton *)sender {
    [[WXApiManager sharedManager] sendAuthRequestWithController:self delegate:self];
}

#pragma mark - WXAuthDelegate
- (void)wxAuthSucceed:(NSString *)code {
    EJSLoginWXRequest *req = [EJSLoginWXRequest new];
    req.code = code;
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        EJSUserTokenModel *tokenModel = response.data;
        [tokenModel save];
        [EJSUserModel syncUserInfo];
        [self dismissViewControllerAnimated:NO completion:nil];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

- (void)wxAuthDenied {
    [[HUDHelper sharedInstance] tipMessage:@"授权失败"];
}

- (IBAction)protocolAction:(UIButton *)sender {
    EJSRegisteProtocolViewController *protocolVC = [[EJSRegisteProtocolViewController alloc] initWithNibName:@"FlyWebViewController" bundle:nil];
    protocolVC.webTitle = @"会员注册协议";
    [self.navigationController pushViewController:protocolVC animated:YES];
}

@end
